package com.hopes.bizz.protocol.hj212.server.handler;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author jie.dai
 */
@Slf4j
public class DataHandlerChain {
    private List<HJ212DataHandler> handlerList = new ArrayList<>();
    /* 标识当前任务处理索引 */
    private ThreadLocal<Integer> indexs = new ThreadLocal<>();

    public boolean handler(String data, DataHandlerChain chain) {
        int index = indexs.get();
        if (index == handlerList.size()) {
            return false;
        }

        HJ212DataHandler handler = handlerList.get(index);
        index++;
        indexs.set(index);
        return handler.handler(data, chain);
    }

    /**
     * 开始处理数据
     *
     * @param data
     */
    public void startHandler(String data) {
        log.debug("开始解析数据 ==> data={},ThreadId={}", data, Thread.currentThread());
        indexs.set(0);
        boolean handlerResult = this.handler(data, this);
        log.info("数据解析结果 ==> handlerResult={}", handlerResult);
        if (!handlerResult) {
            log.info("当前数据未能处理 ==> data={}", data);
        }
    }

    /**
     * 添加数据处理类
     *
     * @param handler
     * @return
     */
    public void addHandler(HJ212DataHandler handler) {
        this.handlerList.add(handler);
    }

    public void addHandlers(Collection<HJ212DataHandler> handlers) {
        this.handlerList.addAll(handlers);
    }

    public void setHandlerList(List<HJ212DataHandler> handlerList) {
        this.handlerList = handlerList;
    }
}
